<template>
  <div class="note-detail-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-icon class="is-loading"><Loading /></el-icon>
      <p>加载中...</p>
    </div>

    <!-- 笔记内容 -->
    <div v-else-if="note" class="note-content">
      <!-- 头部 -->
      <div class="note-header">
        <div class="header-actions">
          <div class="edit-actions">
            <el-button 
              v-if="!isEditing"
              type="success" 
              :icon="Edit" 
              @click="startEdit"
            >
              编辑笔记
            </el-button>
            <template v-else>
              <el-button 
                type="primary" 
                :icon="Check" 
                @click="saveNote"
                :loading="saving"
              >
                保存
              </el-button>
              <el-button 
                :icon="Close" 
                @click="cancelEdit"
              >
                取消
              </el-button>
            </template>
          </div>
        </div>
        
        <div class="note-title-section">
          <div class="title-with-badge">
            <h1 class="note-title" v-if="!isEditing">
              <el-tag type="info" size="large" effect="plain" class="content-type-badge">
                <el-icon><Notebook /></el-icon>
                我的笔记
              </el-tag>
              {{ note.title }}
            </h1>
            <el-input 
              v-else
              v-model="editForm.title"
              placeholder="请输入笔记标题"
              class="title-input"
              size="large"
            />
          </div>
          <div class="note-meta">
            <span class="meta-item">
              <el-icon><Calendar /></el-icon>
              创建时间：{{ note.createdTime }}
            </span>
            <span class="meta-item" v-if="note.updatedTime">
              <el-icon><Edit /></el-icon>
              更新时间：{{ note.updatedTime }}
            </span>
          </div>
        </div>
      </div>

      <!-- 笔记正文 -->
      <div class="note-body">
        <div class="editor-wrapper" v-if="!isEditing">
          <Editor
            v-model="note.content"
            :defaultConfig="viewEditorConfig"
            mode="default"
            style="min-height: 400px;"
          />
        </div>
        <div class="editor-wrapper" v-else>
          <Toolbar
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            mode="default"
          />
          <Editor
            v-model="editForm.content"
            :defaultConfig="editEditorConfig"
            mode="default"
            style="height: 500px; overflow-y: auto;"
            @onCreated="handleCreated"
          />
        </div>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else class="error-container">
      <el-icon class="error-icon"><WarningFilled /></el-icon>
      <p>{{ errorMessage || '笔记不存在或已被删除' }}</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, onBeforeUnmount, shallowRef } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Calendar, Edit, Loading, WarningFilled, Check, Close, Notebook } from '@element-plus/icons-vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import '@wangeditor/editor/dist/css/style.css';
import { getNoteById, updateNote } from '@/api/note';
import { getEditorConfig, getToolbarConfig, createEditorCallback } from '@/utils/editorUtils';
import type { IDomEditor } from '@wangeditor/editor';

const route = useRoute();
const router = useRouter();

// 状态
const loading = ref(true);
const note = ref<any>(null);
const errorMessage = ref('');
const isEditing = ref(false);
const saving = ref(false);

// 富文本编辑器相关
const editorRef = shallowRef<IDomEditor>();
const mode = 'default';
const toolbarConfig = getToolbarConfig();
const handleCreated = createEditorCallback(editorRef);

// 编辑表单
const editForm = reactive({
  title: '',
  content: ''
});

// 查看模式编辑器配置
const viewEditorConfig = {
  readOnly: true,
  scroll: false,
};

// 编辑模式编辑器配置
const editEditorConfig = getEditorConfig('请输入笔记内容...', '我的笔记');

// 获取笔记详情
const fetchNoteDetail = async () => {
  try {
    loading.value = true;
    const noteId = route.query.id;
    
    if (!noteId) {
      errorMessage.value = '缺少笔记ID参数';
      return;
    }

    const fetchData = async () => {
      const response: any = await getNoteById(Number(noteId));
      
      if (response.code === 200) {
        note.value = response.data;
      } else {
        errorMessage.value = response.message || '获取笔记详情失败';
        ElMessage.error(errorMessage.value);
      }
    };

    if (window.requestIdleCallback) {
      window.requestIdleCallback(() => fetchData(), { timeout: 1000 });
    } else {
      setTimeout(() => fetchData(), 0);
    }
  } catch (error: any) {
    console.error('获取笔记详情失败:', error);
    errorMessage.value = error.message || '网络错误，请稍后重试';
    ElMessage.error(errorMessage.value);
  } finally {
    setTimeout(() => { loading.value = false; }, 100);
  }
};

// 开始编辑
const startEdit = () => {
  editForm.title = note.value.title;
  editForm.content = note.value.content;
  isEditing.value = true;
};

// 取消编辑
const cancelEdit = () => {
  ElMessageBox.confirm(
    '确定要取消编辑吗？未保存的内容将会丢失。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    isEditing.value = false;
    editForm.title = '';
    editForm.content = '';
  }).catch(() => {
    // 用户取消
  });
};

// 保存笔记
const saveNote = async () => {
  // 验证标题
  if (!editForm.title || !editForm.title.trim()) {
    ElMessage.warning('请输入笔记标题');
    return;
  }

  // 验证内容
  if (!editForm.content || !editForm.content.trim()) {
    ElMessage.warning('请输入笔记内容');
    return;
  }

  try {
    saving.value = true;
    const response: any = await updateNote({
      id: note.value.id,
      title: editForm.title.trim(),
      content: editForm.content
    });

    if (response.code === 200) {
      ElMessage.success('保存成功');
      // 更新本地数据
      note.value.title = editForm.title.trim();
      note.value.content = editForm.content;
      note.value.updatedTime = new Date().toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
      isEditing.value = false;
    } else {
      ElMessage.error(response.message || '保存失败');
    }
  } catch (error: any) {
    console.error('保存笔记失败:', error);
    ElMessage.error(error.message || '保存失败，请稍后重试');
  } finally {
    saving.value = false;
  }
};

// 返回列表
const goBack = () => {
  if (isEditing.value) {
    ElMessageBox.confirm(
      '当前正在编辑，确定要离开吗？未保存的内容将会丢失。',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      if (editorRef.value) editorRef.value.destroy();
      router.push('/');
    }).catch(() => {
      // 用户取消
    });
  } else {
    if (editorRef.value) editorRef.value.destroy();
    router.push('/');
  }
};

// 组件销毁时清理编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
  }
});

onMounted(() => {
  requestAnimationFrame(() => fetchNoteDetail());
});
</script>

<style scoped>
.note-detail-container {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 60vh;
  color: #909399;
}

.loading-container .el-icon {
  font-size: 48px;
  margin-bottom: 20px;
}

.error-container .error-icon {
  font-size: 64px;
  color: #f56c6c;
  margin-bottom: 20px;
}

.error-container p {
  font-size: 16px;
  margin-bottom: 20px;
}

.note-content {
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.note-header {
  padding: 30px;
  border-bottom: 1px solid #e4e7ed;
}

.header-actions {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 20px;
}

.edit-actions {
  display: flex;
  gap: 10px;
}

.back-button {
  /* 移除了 margin-bottom */
}

.note-title-section {
  /* 移除了 margin-top */
}

.title-with-badge {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.title-with-badge .note-title {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.content-type-badge {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 600;
  padding: 8px 16px;
  border-radius: 20px;
  width: fit-content;
  flex-shrink: 0;
}

.content-type-badge .el-icon {
  font-size: 16px;
}

.note-title {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  font-family: '仿宋', FangSong, STFangsong, serif;
  margin: 0 0 20px 0;
  line-height: 1.4;
}

.title-input {
  margin-bottom: 20px;
}

.title-input :deep(.el-input__wrapper) {
  font-size: 32px;
  font-weight: 600;
  font-family: '仿宋', FangSong, STFangsong, serif;
  padding: 10px 15px;
}

.title-input :deep(.el-input__inner) {
  font-size: 32px;
  font-weight: 600;
  color: #2c3e50;
  font-family: '仿宋', FangSong, STFangsong, serif;
}

.note-meta {
  display: flex;
  gap: 30px;
  flex-wrap: wrap;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #909399;
  font-size: 14px;
}

.meta-item .el-icon {
  font-size: 16px;
}

.note-body {
  padding: 30px;
}

.editor-wrapper {
  min-height: 400px;
  font-family: '仿宋', FangSong, STFangsong, serif;
  font-size: 16px;
  line-height: 1.8;
}

.editor-wrapper :deep(.w-e-text-container) {
  background: transparent !important;
}

.editor-wrapper :deep(.w-e-scroll) {
  background: transparent !important;
}

.editor-wrapper :deep(.w-e-text-placeholder) {
  display: none !important;
}

/* 编辑模式下的样式 */
.editor-wrapper :deep(.w-e-text-container .w-e-scroll) {
  overflow-y: auto !important;
}

/* 查看模式下的样式，让内容完全展示 */
.editor-wrapper :deep(.w-e-text-container[contenteditable="false"]) {
  min-height: auto !important;
  height: auto !important;
}

.editor-wrapper :deep(.w-e-text-container[contenteditable="false"] .w-e-scroll) {
  min-height: auto !important;
  height: auto !important;
  overflow: visible !important;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .note-detail-container {
    padding: 10px;
  }

  .note-header {
    padding: 20px;
  }

  .header-actions {
    flex-direction: column;
    align-items: stretch;
    gap: 15px;
  }

  .edit-actions {
    justify-content: flex-end;
  }

  .note-title {
    font-size: 24px;
  }

  .title-input :deep(.el-input__wrapper),
  .title-input :deep(.el-input__inner) {
    font-size: 24px;
  }

  .note-meta {
    flex-direction: column;
    gap: 10px;
  }

  .note-body {
    padding: 20px;
  }
}
</style>
